package com.minshenglife.zanzan.web.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.minshenglife.zanzan.pub.message.req.BaseMessage;


public class WeixinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static final String Token = "token";//΢�ŷ���Ž����ǵ�Token

	/**
	 * ��������΢�Ź���ƽ̨����֤
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String[] ArrTmp = { Token, timestamp, nonce };
		Arrays.sort(ArrTmp);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ArrTmp.length; i++) {
			sb.append(ArrTmp[i]);
		}
		String pwd = Encrypt(sb.toString());
		String echostr = request.getParameter("echostr");
		System.out.println("pwd=="+pwd);
		System.out.println("echostr=="+echostr);
		if(pwd.equals(signature)){
			if(!"".equals(echostr) && echostr != null){
				response.getWriter().print(echostr);
			}
		}
	}

	/**
	 * ��������ͨ�û�������Ϣ
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StringBuffer sb = new StringBuffer();
		String line;
		BaseMessage xml = null;
//		NodeDao nd = new NodeDaoImpl();
		List list = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
//			xml =//xml2Map(new String(sb.toString().getBytes(),"UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
//		String msgType=map.get("xml.MsgType");
//		if(msgType!=null){
//			if(msgType.equals("text")){
//				sb=textHandler(map);
//			}else if(msgType.equals("image")){
//				sb=imageHandler(map);
//			}else if(msgType.equals("location")){
//				sb=locationHandler(map);
//			}else if(msgType.equals("voice")){
//				sb=voiceHandler(map);
//			}else if(msgType.equals("video")){
//				sb=videoHandler(map);
//			}else if(msgType.equals("link")){
//				sb=linkHandler(map);
//			}else if(msgType.equals("event")){
//				sb=eventHandler(map);
//			}else{
//				
//			}
//		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString());
	}


	private StringBuffer eventHandler(Map<String, String> map) {
		
		return new StringBuffer();
	}

	private StringBuffer linkHandler(Map<String, String> map) {
		return new StringBuffer();
	}

	private StringBuffer videoHandler(Map<String, String> map) {
		return new StringBuffer();
	}

	private StringBuffer voiceHandler(Map<String, String> map) {
		return new StringBuffer();
	}

	private StringBuffer imageHandler(Map<String, String> map) {
		return new StringBuffer();
	}

	private StringBuffer locationHandler(Map<String, String> map) {
		return new StringBuffer();
	}

	private StringBuffer textHandler(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		if(isChinese(map.get("xml.Content"))){
			  sb.append("<xml><ToUserName><![CDATA[").append(map.get("xml.FromUserName"))
			    .append("]]></ToUserName><FromUserName><![CDATA[")
			    .append(map.get("xml.ToUserName"))
			    .append("]]></FromUserName><CreateTime>")
			    .append(map.get("xml.CreateTime"))
			    .append("</CreateTime><MsgType><![CDATA[text]]></MsgType>")
			    .append("<Content><![CDATA[")
			    .append("�Բ���û�в鵽����Ҫ����Ϣ��")
			    .append("]]></Content>")
			 	.append("<FuncFlag>0</FuncFlag></xml>");
			
			  sb.append("]]></Content>")
			 	.append("<FuncFlag>0</FuncFlag></xml>");
		}
	   
		return sb;
	}

	@Override
	public void destroy() {
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		super.init();
	}
	/**
	 * SHA-1����
	 * @param strSrc
	 * @return
	 */
	public String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
	public boolean isChinese(String str){  
	     boolean result=false;  
	     for (int i = 0; i < str.length(); i++){  
	          int chr1 = (char) str.charAt(i);  
	          if(chr1>=19968&&chr1<=171941){//���ַ�Χ \u4e00-\u9fa5 (����)  
	              result = true;  
	          } 
	     }  
	     return result;  
	} 
	
	/*public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		NodeDao nd = new NodeDaoImpl();
		List<TChannelnode> list = nd.getAllChannelnodes("1");
		System.out.println(list.size());
		for(TChannelnode node:list){
			sb.append("��ƣ�").append(node.getName()).append("��")
			.append("��ַ��").append(node.getAddress()).append("\n");
		}
		sb.append("<xml><ToUserName><![CDATA[")
	    .append("]]></ToUserName><FromUserName><![CDATA[")
	    .append("]]></FromUserName><CreateTime>")
	    .append("</CreateTime><MsgType><![CDATA[text]]></MsgType>")
	    .append("<Content><![CDATA[")
	    .append("�Բ���û�в鵽����Ҫ����Ϣ��")
	    .append("]]></Content>")
	 	.append("<FuncFlag>0</FuncFlag></xml>");
		WeixinServlet ws = new WeixinServlet();
		System.out.println(ws.isChinese("1"));
		System.out.println(sb.toString());
	}*/

}
